﻿using AnesSystem.Controls;
using AnesSystem.Models;
using AnesSystem.Services;
using AnesSystem.Util;
using Common;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using System.Windows.Media;

namespace AnesSystem.ViewModels
{
    public class AnesProcessCtrlViewModel : BaseViewModel<AnesProcessCtrlViewModel>
    {
        #region Variables

        private Dictionary<string, CommonBtnCtrlModel> _dicProcess;
        private ObservableCollection<FrameworkElement> _processList;
        private Visibility _visibility = Visibility.Collapsed;
        private bool test = false;
        private bool isEnable = true;
        private bool isNewAddPage = false;


        #endregion


        #region Constructor
        public AnesProcessCtrlViewModel()
        {
            DicProcess = new Dictionary<string, CommonBtnCtrlModel>();
            ProcessList = new ObservableCollection<FrameworkElement>();
            //           InitData();
        }


        #endregion


        #region Properties

        internal Dictionary<string, CommonBtnCtrlModel> DicProcess
        {
            get
            {
                return _dicProcess;
            }

            set
            {
                _dicProcess = value;
            }
        }

        public ObservableCollection<FrameworkElement> ProcessList
        {
            get
            {
                return _processList;
            }

            set
            {
                _processList = value;
            }
        }

        public Visibility Visibility
        {
            get
            {
                return _visibility;
            }

            set
            {
                _visibility = value;
                RaisePropertyChanged("Visibility");
            }
        }

        public bool Test
        {
            get
            {
                return test;
            }

            set
            {
                test = value;
                RaisePropertyChanged("Test");
            }
        }

        public bool IsEnable
        {
            get
            {
                return isEnable;
            }
            set
            {
                isEnable = value;
                RaisePropertyChanged("IsEnable");
            }
        }

        public bool IsNewAddPage
        {
            get
            {
                return isNewAddPage;
            }

            set
            {
                isNewAddPage = value;
            }
        }

        #endregion


        #region 依赖属性


        #endregion


        #region Event


        #endregion


        #region PrivateMethods

        /// <summary>
        /// 初始化页面
        /// </summary>
        private void InitData()
        {
            InitTitle();
            CreateControl();
            //           ChangeTitleStatus();
        }

        /// <summary>
        /// 初始化流程图标
        /// </summary>
        private void InitTitle()
        {
            DicProcess.Clear();
            CommonBtnCtrlModel inRoom = new CommonBtnCtrlModel(Constants.PROCESS_INROOM, true, "--/--");
            DicProcess.Add(Constants.PROCESS_INROOM, inRoom);

            CommonBtnCtrlModel anesStart = new CommonBtnCtrlModel(Constants.PROCESS_ANES_START, false, "--/--");
            DicProcess.Add(Constants.PROCESS_ANES_START, anesStart);

            CommonBtnCtrlModel operStart = new CommonBtnCtrlModel(Constants.PROCESS_OPER_START, false, "--/--");
            DicProcess.Add(Constants.PROCESS_OPER_START, operStart);

            CommonBtnCtrlModel operEnd = new CommonBtnCtrlModel(Constants.PROCESS_OPER_END, false, "--/--");
            DicProcess.Add(Constants.PROCESS_OPER_END, operEnd);

            CommonBtnCtrlModel anesEnd = new CommonBtnCtrlModel(Constants.PROCESS_ANES_END, false, "--/--");
            DicProcess.Add(Constants.PROCESS_ANES_END, anesEnd);

            CommonBtnCtrlModel outRoom = new CommonBtnCtrlModel(Constants.PROCESS_OUTROOM, false, "--/--");
            DicProcess.Add(Constants.PROCESS_OUTROOM, outRoom);
        }
        private void CreateControl()
        {
            try
            {
                foreach (var item in DicProcess.Values)
                {
                    ProcessCtrl ctrl = new ProcessCtrl();
                    ctrl.DataContext = item;
                    ProcessList.Add(ctrl);
                }
            }
            catch (Exception ex)
            {
                Common.LogHelper.Error(GetType().Name, ex);
            }
        }

        /// <summary>
        /// 校验当前手术间是否可以进入
        /// </summary>
        /// <returns></returns>
        private bool VerifyOperRoom()
        {
            string loginRoom = DataManager.Instance.CurRoom.Name;
            if (string.IsNullOrEmpty(loginRoom))
            {
                return false;
            }
            if (PatientLinkService.Instance.IsOperInRoom(loginRoom))
            {
                MessageBoxCommon.ShowDialog("当前手术间正在进行手术，无法进行新手术!", MessageBoxCommon.OK);
                return false;
            }
            if (!loginRoom.Equals(DataManager.Instance.CurrentPatientLink.Schedule.Pbssjh))
            {
                MessageBoxCommon.ShowDialog("此手术间只能进行" + loginRoom + "号手术间手术!", MessageBoxCommon.OK);
                return false;
            }
            else
            {
                return true;
            }
        }
        private void ChangeTitleStatus()
        {
            DicProcess[Constants.PROCESS_ANES_START].State = true;
            DicProcess[Constants.PROCESS_OPER_START].State = true;
            DicProcess[Constants.PROCESS_OPER_END].State = false;
            DicProcess[Constants.PROCESS_ANES_END].State = false;
            DicProcess[Constants.PROCESS_OUTROOM].State = true;
        }
        public void InRoom(DateTime date)
        {
            string status = Constants.OR_STATUS_FLAG_IN_ROOM;
            DataManager.Instance.CurrentPatientLink.Application.Detailstatus = status;
            DataManager.Instance.CurrentPatientLink.Application.Status = Constants.AP_STATUS_MAZUIZHONG;
            date = date.AddSeconds(-date.Second).AddMilliseconds(-date.Millisecond);
            DataManager.Instance.CurrentPatientLink.Status.InRoomTime = date;
            date = date.AddMinutes(-date.Minute % 15);
            DataManager.Instance.CurrentPatientLink.Status.AnesRecordStartTime = date;
            InitOperInfo4InRoom();
            SaveOper2DB();

        }
        public void OutRoom(DateTime date)
        {
            string status = Constants.OR_STATUS_FLAG_OUT_ROOM;
            DataManager.Instance.CurrentPatientLink.Application.Detailstatus = status;
            DataManager.Instance.CurrentPatientLink.Application.Status = Constants.AP_STATUS_MAZUIHOU;
            date = date.AddSeconds(-date.Second).AddMilliseconds(-date.Millisecond); ;
            DataManager.Instance.CurrentPatientLink.Status.OutRoomTime = date;
            if ((!DataManager.Instance.CurrentPatientLink.Status.MazuiStartTime.Equals(new DateTime())) && (!DataManager.Instance.CurrentPatientLink.Status.MazuiEndTime.Equals(new DateTime())))
            {
                TimeSpan span = DataManager.Instance.CurrentPatientLink.Status.MazuiEndTime - DataManager.Instance.CurrentPatientLink.Status.MazuiStartTime;
                long anesMinutes = span.Days * 24 * 60 + span.Hours * 60 + span.Minutes;
                if (anesMinutes > 0)
                {
                    DataManager.Instance.CurrentPatientLink.Status.MazuiSpanTime = anesMinutes;
                }
            }
            if ((!DataManager.Instance.CurrentPatientLink.Status.OperStartTime.Equals(new DateTime())) && (!DataManager.Instance.CurrentPatientLink.Status.OperEndTime.Equals(new DateTime())))
            {
                TimeSpan span = DataManager.Instance.CurrentPatientLink.Status.OperEndTime - DataManager.Instance.CurrentPatientLink.Status.OperStartTime;
                long operMinutes = span.Days * 24 * 60 + span.Hours * 60 + span.Minutes;
                if (operMinutes > 0)
                {
                    DataManager.Instance.CurrentPatientLink.Status.OperSpanTime = operMinutes;
                }
            }
            SaveOper2DB();
        }

        private void SaveOper2DB()
        {
            PatientLinkService.Instance.Update(DataManager.Instance.CurrentPatientLink);
        }

        /// <summary>
        /// 入室初始化患者信息
        /// </summary>
        private void InitOperInfo4InRoom()
        {
            AnesthesiaRecordModel anesthesiaRecord = DataManager.Instance.CurrentPatientLink.AnesthesiaRecord;
            ApplicationModel application = DataManager.Instance.CurrentPatientLink.Application;
            anesthesiaRecord.Nsss1 = (string)MakeACopy(application.Nsssmc);
            anesthesiaRecord.Nsss2 = (string)MakeACopy(application.Nsssmc1);
            anesthesiaRecord.Nsss3 = (string)MakeACopy(application.Nsssmc2);
            anesthesiaRecord.Nsss4 = (string)MakeACopy(application.Nsssmc3);

            anesthesiaRecord.Shzd1 = (string)MakeACopy(application.Sqzd1);
            anesthesiaRecord.Shzd2 = (string)MakeACopy(application.Sqzd2);
            anesthesiaRecord.Shzd3 = (string)MakeACopy(application.Sqzd3);
            anesthesiaRecord.Shzd4 = (string)MakeACopy(application.Sqzd4);
            anesthesiaRecord.Shzd5 = (string)MakeACopy(application.Sqzd5);

            anesthesiaRecord.Ysss1 = (string)MakeACopy(application.Nsssmc);
            anesthesiaRecord.Ysss2 = (string)MakeACopy(application.Nsssmc1);
            anesthesiaRecord.Ysss3 = (string)MakeACopy(application.Nsssmc2);
            anesthesiaRecord.Ysss4 = (string)MakeACopy(application.Nsssmc3);

            anesthesiaRecord.Sqzd = (string)MakeACopy(application.Sqzd1);

            if (string.IsNullOrEmpty(application.Ssysbh))
            {
                anesthesiaRecord.OperDoctor1 = (string)MakeACopy(application.Ssysxm);
            }
            else
            {
                anesthesiaRecord.OperDoctor1 = (string)MakeACopy(application.Ssysbh);
            }
            anesthesiaRecord.OperDoctor2 = (string)MakeACopy(application.Zlysbh1);
            anesthesiaRecord.OperDoctor3 = (string)MakeACopy(application.Zlysbh2);
            ScheduleModel schedule = DataManager.Instance.CurrentPatientLink.Schedule;
            anesthesiaRecord.Mzbh = Util.ExtensionMethods.GetAnesID();

            if (string.IsNullOrEmpty(anesthesiaRecord.Zmys))
            {
                anesthesiaRecord.Zmys = (string)MakeACopy(schedule.Mzysbh1);
            }
            if (anesthesiaRecord.Fmys1 == null)
            {
                anesthesiaRecord.Fmys1 = (string)MakeACopy(schedule.Mzysbh2);
            }
            if (anesthesiaRecord.Xhhs1 == null)
            {
                anesthesiaRecord.Xhhs2 = (string)MakeACopy(schedule.Xhhsbh1);
            }
            if (anesthesiaRecord.Xshs1 == null)
            {
                anesthesiaRecord.Xshs1 = (string)MakeACopy(schedule.Qxhsbh1);
            }
            anesthesiaRecord.Mzff = (string)MakeACopy(application.Mzfs);

            AsaModel asa = DataManager.Instance.CurrentPatientLink.AnesthesiaRecord.Asa;
            asa.Level = (string)MakeACopy(application.Asa);
            if (Constants.OR_TYPE_URGENT.Equals(application.Type))
            {
                asa.Jz = true;
            }
            else
            {
                asa.Zq = true;
            }

        }

        /// <summary>
        /// 添加事件
        /// </summary>
        /// <param name="code"></param>
        /// <param name="date"></param>
        public void AddEvent(string code, DateTime date, bool isRefresh, bool isEnd)
        {
            List<PatientEventsModel> eventList = GetSortEventsByCode(code);
            PatientEventsModel pem = null;
            if (eventList == null || eventList.Count == 0)
            {
                pem = new PatientEventsModel();
                if (!isEnd)
                {
                    pem.Code = code;
                    pem.BeginTime = date;
                    pem.PatientID = DataManager.Instance.CurrentPatientLink.Id.ToString();
                }
            }
            if (eventList != null && eventList.Count > 0)
            {
                pem = eventList.Last();
            }
            if (!isEnd)
            {
                pem.BeginTime = date;
            }
            else
            {
                pem.EndTime = date;
            }
            PatientEventsService.Instance.AddUpdate(pem);
            OperationDataPool.Instance.CurOperationData.EventDataCache.AddUpdateEvent(pem);
            //刷新事件一栏
            if (isRefresh)
            {
                RefreshEvent();
            }

        }

        private void RefreshEvent()
        {
            for (int i = 1; i <= DataManager.Instance.CurrentPatientLink.Status.TotalPage; i++)
            {
                (DataManager.Instance.AnesRecordCtrl.DataContext as AnesRecordCtrlViewModel).AnesRecordCtrlViewModels[i].AnesEventAndMedicineCtrlViewModel.Refresh();
            }
        }

        /// <summary>
        /// 获取已存在事件并排序
        /// </summary>
        /// <param name="code"></param>
        /// <returns></returns>
        private List<PatientEventsModel> GetSortEventsByCode(string code)
        {
            DateTime startTime = PatientLink.Status.InRoomTime;
            DateTime anesStartTime = PatientLink.Status.AnesRecordStartTime;
            DateTime endTime;
            if (!PatientLink.Status.OutRoomTime.Equals(new DateTime()))
            {
                endTime = PatientLink.Status.OutRoomTime;
            }
            else
            {
                endTime = anesStartTime.AddHours((PatientLink.Status.TotalPage) * 4);
            }
            List<PatientEventsModel> tempList = PatientEventsService.Instance.GetPatientEvents8Time(PatientLink.Id.ToString(), startTime, endTime);
            List<PatientEventsModel> eventList = new List<PatientEventsModel>();
            if (tempList != null || tempList.Count > 0)
            {
                foreach (var item in tempList)
                {
                    if (code.Equals(item.Code))
                    {
                        eventList.Add(item);
                    }
                }
            }
            if (eventList != null || eventList.Count > 0)
            {
                eventList.Sort((PatientEventsModel o1, PatientEventsModel o2) =>
                {
                    if (o1.BeginTime > o2.BeginTime)
                    {
                        return 1;
                    }
                    else if (o1.BeginTime < o2.BeginTime)
                    {
                        return -1;
                    }
                    else
                    {
                        return 0;
                    }
                });
                return eventList;
            }
            else
            {
                return null;
            }
        }

        /// <summary>
        /// 添加手术状态
        /// </summary>
        private void AddOperStatus(string code, DateTime date)
        {
            for (int i = 1; i <= DataManager.Instance.CurrentPatientLink.Status.TotalPage; i++)
            {
                (DataManager.Instance.AnesRecordCtrl.DataContext as AnesRecordCtrlViewModel).AnesRecordCtrlViewModels[i].OperStatusItemCtrlViewModel.Refresh();
            }
        }

        private object MakeACopy(object obj)
        {
            if (null == obj)
            {
                return null;
            }
            if (obj.GetType().Equals(typeof(string)))
            {
                return obj.ToString();
            }
            if (obj.GetType().Equals(typeof(DateTime)))
            {
                return (DateTime)obj;
            }
            else
            {
                return null;
            }
        }

        /// <summary>
        /// 恢复为初始状态
        /// </summary>
        private void Clear()
        {
            ProcessList.Clear();
            DicProcess.Clear();
            InitData();


        }

        /// <summary>
        /// 计算麻醉单页数
        /// </summary>
        private void CalTotalPage()
        {
            if (DataManager.Instance.CurrentHospital.HospitalCode.Equals(HospitalConfig.HOSPITAL_CODE_CQ_FYBJY))
            {
                RefCurTatalPage();
            }
            else
            {
                DateTime startTime = DataManager.Instance.CurrentPatientLink.Status.AnesRecordStartTime;
                DateTime endTime = DataManager.Instance.CurrentPatientLink.Status.OutRoomTime;
                if (endTime.Equals(new DateTime()))
                {
                    endTime = DateTime.Now;
                }
                TimeSpan span = endTime - startTime;
                int minutes = span.Days * 24 * 60 + span.Hours * 60 + span.Minutes;
                if (minutes < 0)
                {
                    minutes = 0;
                }
                int temp = minutes % (4 * 60);
                int totalPage = 0;
                if (temp == 0 && minutes != 0)
                {
                    totalPage = (int)minutes / (4 * 60);
                }
                else
                {
                    totalPage = (int)minutes / (4 * 60) + 1;
                }
                DataManager.Instance.CurrentPatientLink.Status.TotalPage = totalPage;
                SaveOper2DB();
            }
        }

        /// <summary>
        /// 入手术室按钮触发
        /// </summary>
        private void InRoomClick()
        {
            if (VerifyOperRoom())
            {
                DateTime date = new DateTime();
                CusDatePickerWin win = new CusDatePickerWin();
                win.SelectedDateTime = DateTime.Now;
                win.ShowDialog();
                if (win.Result)
                {
                    date = win.SelectedDateTime;
                }

                if (!date.Equals(new DateTime()))
                {
                    ChangeTitleStatus();
                    DicProcess[Constants.PROCESS_INROOM].TimeText = date.ToString(DateFormat.DATE_FORMAT_STR_HM);
                    DicProcess[Constants.PROCESS_INROOM].State = false;
                    if (DataManager.Instance.CurrentHospital.HospitalCode.Equals(HospitalConfig.HOSPITAL_CODE_SC_SCDC))
                    {
                        FunctionListHeaderCtrlViewModel.Instance.DisplayButton(true, FunctionListButton.刷新, FunctionListButton.全屏, FunctionListButton.打印, FunctionListButton.手术详情, FunctionListButton.模板, FunctionListButton.储存模板, FunctionListButton.取消手术, FunctionListButton.术中输血);
                    }
                    else
                    {
                        FunctionListHeaderCtrlViewModel.Instance.DisplayButton(true, FunctionListButton.刷新, FunctionListButton.全屏, FunctionListButton.打印, FunctionListButton.手术详情, FunctionListButton.模板, FunctionListButton.储存模板, FunctionListButton.取消手术);
                    }
                    if (DataManager.Instance.CurrentPatientLink.VitalSignShow != null)
                    {
                        List<ConfigVitalSignsModel> list = DataManager.Instance.CurrentPatientLink.VitalSignShow.VitalSign;
                        if (list == null || list.Count == 0)
                        {
                            DataManager.Instance.CurrentPatientLink.VitalSignShow.VitalSign.AddRange(RealTimeSignsConfigCtrlViewModel.Instance.GetAutoShow());
                        }
                    }
                    else
                    {
                        DataManager.Instance.CurrentPatientLink.VitalSignShow.VitalSign.AddRange(RealTimeSignsConfigCtrlViewModel.Instance.GetAutoShow());
                    }
                    Common.LogHelper.Info(this.GetType(), "入室自动加载生命体征条数：" + RealTimeSignsConfigCtrlViewModel.Instance.GetAutoShow().Count);
                    InRoom(date);
                    //DateTime startTime = DataManager.Instance.CurrentPatientLink.Status.AnesRecordStartTime;
                    //DateTime endTime = DataManager.Instance.CurrentPatientLink.Status.OutRoomTime;
                    //if (endTime.Equals(new DateTime()))
                    //{
                    //    endTime = DateTime.Now;
                    //}
                    //TimeSpan span = endTime - startTime;
                    //int minutes = span.Days * 24 * 60 + span.Hours * 60 + span.Minutes;
                    //int totalPage = (int)minutes / (4 * 60) + 1;
                    //DataManager.Instance.CurrentPatientLink.Status.TotalPage = totalPage;
                    CalTotalPage();
                    //采集数据开始启动
                    VitalSignCapture.Instance.StartCapture();
                    //添加事件
                    AddEvent(Constants.EVENT_IN_ROOM, date, false, false);
                    //添加状态
                    //                   AddOperStatus(Constants.EVENT_IN_ROOM,date);
                    Common.LogHelper.Info(this.GetType(), "The patient In_Room");
                    //展现麻醉单
                    (DataManager.Instance.AnesRecordCtrl.ViewModel as AnesRecordCtrlViewModel).InitData();
                    //回传状态
                    HospitalReturnUtil.Instance.ReturnOperStatus2His(GetPatientLink());

                }
            }
        }



        /// <summary>
        ///麻醉开始按钮触发 
        /// </summary>
        private void AnesStartClick()
        {
            if (DataManager.Instance.CurrentHospital.HospitalCode.Equals(HospitalConfig.HOSPITAL_CODE_CQ_NTZYY))
            {
                MessageBoxCommon.ShowDialog("请确认是否检查：钠石灰、呼吸回路、氧源、报警界限、吸引器。", MessageBoxCommon.OK);
            }
            DateTime date = new DateTime();
            CusDatePickerWin win = new CusDatePickerWin();
            win.SelectedDateTime = DateTime.Now;
            win.ShowDialog();
            if (win.Result)
            {
                date = win.SelectedDateTime;
            }
            if (!date.Equals(new DateTime()))
            {
                if (date.CompareTo(DataManager.Instance.CurrentPatientLink.Status.InRoomTime) <= 0)
                {
                    MessageBoxCommon.ShowDialog("麻醉开始时间应大于入室时间!", MessageBoxCommon.OK);
                    return;
                }
                DicProcess[Constants.PROCESS_ANES_START].TimeText = date.ToString(DateFormat.DATE_FORMAT_STR_HM);
                DicProcess[Constants.PROCESS_ANES_START].State = false;
                DicProcess[Constants.PROCESS_ANES_END].State = true;
                DataManager.Instance.CurrentPatientLink.Status.MazuiStartTime = date;
                SaveOper2DB();
                AddEvent(Constants.EVENT_ANES, date, true, false);
                AddOperStatus(Constants.ANESTHETIC_START, date);
                Common.LogHelper.Info(this.GetType(), "The patient Anes_Starting");
            }
        }

        /// <summary>
        /// 手术开始按钮触发
        /// </summary>
        private void OperStartClick()
        {

            DateTime date = new DateTime();
            CusDatePickerWin win = new CusDatePickerWin();
            win.SelectedDateTime = DateTime.Now;
            win.ShowDialog();
            if (win.Result)
            {
                date = win.SelectedDateTime;
            }
            if (!date.Equals(new DateTime()))
            {
                if (date.CompareTo(DataManager.Instance.CurrentPatientLink.Status.InRoomTime) <= 0)
                {
                    MessageBoxCommon.ShowDialog("手术开始时间应大于入室时间!", MessageBoxCommon.OK);
                    return;
                }
                DicProcess[Constants.PROCESS_OPER_START].TimeText = date.ToString(DateFormat.DATE_FORMAT_STR_HM);
                DicProcess[Constants.PROCESS_OPER_START].State = false;
                DicProcess[Constants.PROCESS_OPER_END].State = true;
                DataManager.Instance.CurrentPatientLink.Status.OperStartTime = date;
                SaveOper2DB();
                AddEvent(Constants.EVENT_OPERATION, date, true, false);
                AddOperStatus(Constants.OPERATION_START, date);
                Common.LogHelper.Info(this.GetType(), "The patient Oper_Starting");
            }
        }

        /// <summary>
        /// 手术结束按钮触发
        /// </summary>
        private void OperEndClick()
        {
            DateTime date = new DateTime();
            CusDatePickerWin win = new CusDatePickerWin();
            win.SelectedDateTime = DateTime.Now;
            win.ShowDialog();
            if (win.Result)
            {
                date = win.SelectedDateTime;
            }
            if (!date.Equals(new DateTime()))
            {
                if (date.CompareTo(DataManager.Instance.CurrentPatientLink.Status.OperStartTime) <= 0)
                {
                    MessageBoxCommon.ShowDialog("手术结束时间应大于开始时间!", MessageBoxCommon.OK);
                    return;
                }
                DicProcess[Constants.PROCESS_OPER_END].TimeText = date.ToString(DateFormat.DATE_FORMAT_STR_HM);
                DicProcess[Constants.PROCESS_OPER_END].State = false;
                DataManager.Instance.CurrentPatientLink.Status.OperEndTime = date;
                SaveOper2DB();
                AddEvent(Constants.EVENT_OPERATION, date, true, true);
                AddOperStatus(Constants.OPERATION_END, date);
                Common.LogHelper.Info(this.GetType(), "The patient Oper_Endding");
            }
        }

        /// <summary>
        /// 麻醉结束按钮触发
        /// </summary>
        private void AnesEndClick()
        {
            DateTime date = new DateTime();
            CusDatePickerWin win = new CusDatePickerWin();
            win.SelectedDateTime = DateTime.Now;
            win.ShowDialog();
            if (win.Result)
            {
                date = win.SelectedDateTime;
            }
            if (!date.Equals(new DateTime()))
            {
                if (date.CompareTo(DataManager.Instance.CurrentPatientLink.Status.MazuiStartTime) <= 0)
                {
                    MessageBoxCommon.ShowDialog("麻醉结束时间应大于开始时间!", MessageBoxCommon.OK);
                    return;
                }
                DicProcess[Constants.PROCESS_ANES_END].TimeText = date.ToString(DateFormat.DATE_FORMAT_STR_HM);
                DicProcess[Constants.PROCESS_ANES_END].State = false;
                DataManager.Instance.CurrentPatientLink.Status.MazuiEndTime = date;
                SaveOper2DB();
                AddEvent(Constants.EVENT_ANES, date, true, true);
                AddOperStatus(Constants.ANESTHETIC_START, date);
                Common.LogHelper.Info(this.GetType(), "The patient Anes_Endding");
            }
        }

        /// <summary>
        /// 出手术室按钮触发
        /// </summary>
        private void OutRoomClick()
        {
            if (!CheckZhiKong() && !HospitalConfig.Instance.CurrentHospital.HospitalCode.Equals(HospitalConfig.HOSPITAL_CODE_SC_CD_TYFSYY))
            {
                MessageBoxCommon.ShowDialog("您未填写质控!", MessageBoxCommon.OK);
                return;
            }
            if (HospitalConfig.Instance.CurrentHospital.HospitalCode.Equals(HospitalConfig.HOSPITAL_CODE_CQ_RCQRMYY) && !CheckGanRanXinxi())
            {
                MessageBoxCommon.ShowDialog("您未填写感染信息!", MessageBoxCommon.OK);
                return;
            }
            if (string.IsNullOrEmpty(DataManager.Instance.CurrentPatientLink.AnesthesiaRecord.Zmys))
            {
                if (MessageBoxCommon.ShowDialog("尚未填写主麻医师，是否确认退出?", MessageBoxCommon.OKCANCLE).Value == false)
                {
                    return;
                }
            }

            DateTime date = new DateTime();
            CusDatePickerWin win = new CusDatePickerWin();
            win.SelectedDateTime = DateTime.Now;
            win.ShowDialog();
            if (win.Result)
            {
                date = win.SelectedDateTime;
            }
            if (!date.Equals(new DateTime()))
            {
                if (date.CompareTo(DataManager.Instance.CurrentPatientLink.Status.InRoomTime) <= 0)
                {
                    MessageBoxCommon.ShowDialog("出室时间应大于入室时间!", MessageBoxCommon.OK);
                    return;
                }
                if ((date - DataManager.Instance.CurrentPatientLink.Status.InRoomTime).TotalMinutes > 24 * 60)
                {
                    MessageBoxCommon.ShowDialog("手术时长应小于24小时!", MessageBoxCommon.OK);
                    return;
                }
                DicProcess[Constants.PROCESS_OUTROOM].TimeText = date.ToString(DateFormat.DATE_FORMAT_STR_HM);
                DicProcess[Constants.PROCESS_OUTROOM].State = false;
                if (DataManager.Instance.CurrentHospital.HospitalCode.Equals(HospitalConfig.HOSPITAL_CODE_SC_SCDC))
                {
                    FunctionListHeaderCtrlViewModel.Instance.DisplayButton(true, FunctionListButton.刷新, FunctionListButton.取消手术, FunctionListButton.打印, FunctionListButton.手术详情, FunctionListButton.储存模板, FunctionListButton.全屏, FunctionListButton.术中输血);
                }
                else
                {
                    FunctionListHeaderCtrlViewModel.Instance.DisplayButton(true, FunctionListButton.刷新, FunctionListButton.取消手术, FunctionListButton.打印, FunctionListButton.手术详情, FunctionListButton.储存模板, FunctionListButton.全屏);
                }
                //停止采集
                VitalSignCapture.Instance.StopCapture();
                OutRoom(date);
                //添加事件
                AddEvent(Constants.EVENT_IN_ROOM, date, true, true);
                //计算页数
                CalTotalPage();
                //刷新页面
                Refresh();
                //                RefreshMedicineAndInfusion();
                //计算公分
                CalWorkSocre();
                //回传状态
                HospitalReturnUtil.Instance.ReturnOperStatus2His(GetPatientLink());

            }
        }

        /// <summary>
        /// 荣昌判断感染信息是否填写
        /// </summary>
        /// <returns></returns>
        private bool CheckGanRanXinxi()
        {
            bool flag = false;
            InfectionModel ganran = DataManager.Instance.CurrentPatientLink.Infection;
            Type type = ganran.GetType();
            foreach (PropertyInfo p in type.GetProperties())
            {
                if (p.PropertyType == typeof(bool) && (bool)p.GetValue(ganran))
                {
                    flag = true;
                    break;
                }
            }
            return flag;
        }

        //公分计算
        private void CalWorkSocre()
        {
            if (DataManager.Instance.CurrentHospital.HospitalCode.Equals(HospitalConfig.HOSPITAL_CODE_CQ_RCQRMYY))
            {
                WorkScoreRCViewModel.Instance.CalWorkScore();
            }
        }



        /// <summary>
        /// 判断质控是否提交
        /// </summary>
        /// <returns></returns>
        private bool CheckZhiKong()
        {
            bool flag = false;
            QualityPojoModel zhiKong = DataManager.Instance.CurrentPatientLink.QualityPojo;
            Type type = zhiKong.GetType();
            foreach (PropertyInfo p in type.GetProperties())
            {
                if (p.PropertyType == typeof(bool) && (bool)p.GetValue(zhiKong))
                {
                    flag = true;
                    break;
                }
            }
            return flag;

        }

        /// <summary>
        /// 删除所有麻醉单数据
        /// </summary>
        private void DelAllExe()
        {
            DateTime startTime = GetPatientLink().Status.AnesRecordStartTime;
            DateTime endTime = startTime.AddDays(1);
            //status
            GetPatientLink().Status.InRoomTime = new DateTime();
            GetPatientLink().Status.OperStartTime = new DateTime();
            GetPatientLink().Status.OperEndTime = new DateTime();
            GetPatientLink().Status.MazuiStartTime = new DateTime();
            GetPatientLink().Status.MazuiEndTime = new DateTime();
            GetPatientLink().Status.OutRoomTime = new DateTime();
            GetPatientLink().Status.AnesRecordStartTime = new DateTime();
            GetPatientLink().Status.OperSpanTime = 0;
            GetPatientLink().Status.MazuiSpanTime = 0;
            //event
            List<PatientEventsModel> eventExeList = OperationDataPool.Instance.CurOperationData.EventDataCache.SearchAllEventExe();
            foreach (var item in eventExeList)
            {
                PatientEventsService.Instance.DeleteById(item.Id);
            }
            OperationDataPool.Instance.CurOperationData.EventDataCache.ClearCache();
            InitTitle();
            //           ChangeTitleStatus();
            //drug
            foreach (var item in OperationDataPool.Instance.CurOperationData.DrugsDataCache.AllPatientDrugsList)
            {
                PatientDrugsService.Instance.DelOneExe(item);
            }
            OperationDataPool.Instance.CurOperationData.DrugsDataCache.ClearCache();
            //vitalSign
            List<PatientVitalSignsModel> vitalList = PatientVitalSignsServicie.Instance.GetVitalByTime(GetPatientLink().Id.ToString(), startTime, endTime);
            foreach (var item in vitalList)
            {
                PatientVitalSignsServicie.Instance.DeleteById(item.Id);
            }
            OperationDataPool.Instance.CurOperationData.VitalSignDataCache.ClearCache();
            //Cache
            //   DataManager.Instance.RemoveCurPatientLink(GetPatientLink().Id);
        }

        /// <summary>
        /// 计算统计所需数据
        /// </summary>
        private void CalTimeSpan()
        {
            if ((!DataManager.Instance.CurrentPatientLink.Status.MazuiStartTime.Equals(new DateTime())) && (!DataManager.Instance.CurrentPatientLink.Status.MazuiEndTime.Equals(new DateTime())))
            {
                TimeSpan span = DataManager.Instance.CurrentPatientLink.Status.MazuiEndTime - DataManager.Instance.CurrentPatientLink.Status.MazuiStartTime;
                long anesMinutes = span.Days * 24 * 60 + span.Hours * 60 + span.Minutes;
                if (anesMinutes > 0)
                {
                    DataManager.Instance.CurrentPatientLink.Status.MazuiSpanTime = anesMinutes;
                }
            }
            if ((!DataManager.Instance.CurrentPatientLink.Status.OperStartTime.Equals(new DateTime())) && (!DataManager.Instance.CurrentPatientLink.Status.OperEndTime.Equals(new DateTime())))
            {
                TimeSpan span = DataManager.Instance.CurrentPatientLink.Status.OperEndTime - DataManager.Instance.CurrentPatientLink.Status.OperStartTime;
                long operMinutes = span.Days * 24 * 60 + span.Hours * 60 + span.Minutes;
                if (operMinutes > 0)
                {
                    DataManager.Instance.CurrentPatientLink.Status.OperSpanTime = operMinutes;
                }
            }
        }

        #endregion


        #region Public/ProtectedMethods


        /// <summary>
        /// 麻醉单加载
        /// </summary>
        public void LoadData()
        {
            Clear();
            InitAnesData();
        }

        public void ChangeTotalPage()
        {
            DataManager.Instance.CurrentPatientLink = PatientLinkService.Instance.GetObjById(DataManager.Instance.CurrentPatientLink.Id.ToString());
            if (DataManager.Instance.PatientLinkCache.ContainsKey(DataManager.Instance.CurrentPatientLink.Id))
            {
                BaseTableControl ctrl = DataManager.Instance.AnesRecordCtrl;
                ctrl.IsNewCreate = true;
            }
            LoadData();
        }


        public override void Refresh()
        {
            Common.LogHelper.Info(this.GetType(), "the anesRecord is Refreshing");
            if (GetPatientLink().Application.Detailstatus.Equals(Constants.OR_STATUS_FLAG_DISCHARGED) || (GetPatientLink() != null && GetPatientLink().Application.Detailstatus.Equals(Constants.OR_STATUS_FLAG_SCHEDULED)))
            {
                if (GetPatientLink().Application.Detailstatus.Equals(Constants.OR_STATUS_FLAG_DISCHARGED))
                {
                    DataManager.Instance.CurrentPatientLink = null;
                }
                GotoSelOperCtrl();
                return;
            }
            DataManager.Instance.CurrentPatientLink = PatientLinkService.Instance.GetObjById(DataManager.Instance.CurrentPatientLink.Id.ToString());
            if (DataManager.Instance.PatientLinkCache.ContainsKey(DataManager.Instance.CurrentPatientLink.Id))
            {
                BaseTableControl ctrl = DataManager.Instance.AnesRecordCtrl;
                ctrl.IsNewCreate = true;
            }
            LoadData();
        }
        public void RefreshMedicineAndInfusion()
        {
            for (int i = 1; i <= DataManager.Instance.CurrentPatientLink.Status.TotalPage; i++)
            {
                (DataManager.Instance.AnesRecordCtrl.DataContext as AnesRecordCtrlViewModel).AnesRecordCtrlViewModels[i].AnesMedicineCtrlViewModel.Refresh();
                (DataManager.Instance.AnesRecordCtrl.DataContext as AnesRecordCtrlViewModel).AnesRecordCtrlViewModels[i].AnesInfusionCtrlViewModel.Refresh();
            }
        }

        /// <summary>
        /// 初始化历史数据
        /// </summary>
        /// <param name="isChange"></param>
        public void InitAnesData()
        {
            if (!DataManager.Instance.CurrentPatientLink.Status.InRoomTime.Equals(new DateTime()))
            {
                if (DataManager.Instance.CurrentHospital.HospitalCode.Equals(HospitalConfig.HOSPITAL_CODE_SC_SCDC))
                {
                    FunctionListHeaderCtrlViewModel.Instance.DisplayButton(true, FunctionListButton.刷新, FunctionListButton.打印, FunctionListButton.手术详情, FunctionListButton.模板, FunctionListButton.储存模板, FunctionListButton.全屏, FunctionListButton.取消手术, FunctionListButton.术中输血);
                }
                else
                {
                    FunctionListHeaderCtrlViewModel.Instance.DisplayButton(true, FunctionListButton.刷新, FunctionListButton.打印, FunctionListButton.手术详情, FunctionListButton.模板, FunctionListButton.储存模板, FunctionListButton.全屏, FunctionListButton.取消手术);
                }
                DicProcess[Constants.PROCESS_INROOM].TimeText = (DataManager.Instance.CurrentPatientLink.Status.InRoomTime.ToString(DateFormat.DATE_FORMAT_STR_HM));
                DicProcess[Constants.PROCESS_INROOM].State = false;
                CheckEventAndTitle();
                CalTotalPage();
                if (DataManager.Instance.CurrentPatientLink.Status.OutRoomTime.Equals(new DateTime()))
                {
                    DicProcess[Constants.PROCESS_OUTROOM].State = true;

                    if (DataManager.Instance.CurrentPatientLink.Schedule.Pbssjh.Equals(DataManager.Instance.CurRoom.Name))
                    {
                        VitalSignCapture.Instance.StartCapture();
                    }
                }
                else
                {
                    DicProcess[Constants.PROCESS_OUTROOM].TimeText = DataManager.Instance.CurrentPatientLink.Status.OutRoomTime.ToString(DateFormat.DATE_FORMAT_STR_HM);
                    DicProcess[Constants.PROCESS_OUTROOM].State = false;
                    if (DataManager.Instance.CurrentHospital.HospitalCode.Equals(HospitalConfig.HOSPITAL_CODE_SC_SCDC))
                    {
                        FunctionListHeaderCtrlViewModel.Instance.DisplayButton(true, FunctionListButton.刷新, FunctionListButton.打印, FunctionListButton.取消手术, FunctionListButton.手术详情, FunctionListButton.储存模板, FunctionListButton.全屏, FunctionListButton.术中输血);
                    }
                    else if (DataManager.Instance.CurrentHospital.HospitalCode.Equals(HospitalConfig.HOSPITAL_CODE_BOCHUANG))
                    {
                        FunctionListHeaderCtrlViewModel.Instance.DisplayButton(true, FunctionListButton.刷新, FunctionListButton.打印, FunctionListButton.取消手术, FunctionListButton.手术详情, FunctionListButton.储存模板, FunctionListButton.全屏, FunctionListButton.实时监控);
                    }
                    else
                    {
                        FunctionListHeaderCtrlViewModel.Instance.DisplayButton(true, FunctionListButton.刷新, FunctionListButton.打印, FunctionListButton.取消手术, FunctionListButton.手术详情, FunctionListButton.储存模板, FunctionListButton.全屏);
                    }
                }
                if (!DataManager.Instance.CurrentPatientLink.Status.OperStartTime.Equals(new DateTime()))
                {
                    DicProcess[Constants.PROCESS_OPER_START].TimeText = DataManager.Instance.CurrentPatientLink.Status.OperStartTime.ToString(DateFormat.DATE_FORMAT_STR_HM);
                    DicProcess[Constants.PROCESS_OPER_START].State = false;
                    if (!DataManager.Instance.CurrentPatientLink.Status.OperEndTime.Equals(new DateTime()))
                    {
                        DicProcess[Constants.PROCESS_OPER_END].TimeText = DataManager.Instance.CurrentPatientLink.Status.OperEndTime.ToString(DateFormat.DATE_FORMAT_STR_HM);
                        DicProcess[Constants.PROCESS_OPER_END].State = false;
                    }
                    else
                    {
                        DicProcess[Constants.PROCESS_OPER_END].State = true;
                    }
                }
                else
                {
                    DicProcess[Constants.PROCESS_OPER_START].State = true;
                    DicProcess[Constants.PROCESS_OPER_END].State = false;
                }

                if (!DataManager.Instance.CurrentPatientLink.Status.MazuiStartTime.Equals(new DateTime()))
                {
                    DicProcess[Constants.PROCESS_ANES_START].TimeText = DataManager.Instance.CurrentPatientLink.Status.MazuiStartTime.ToString(DateFormat.DATE_FORMAT_STR_HM);
                    DicProcess[Constants.PROCESS_ANES_START].State = false;
                    if (!DataManager.Instance.CurrentPatientLink.Status.MazuiEndTime.Equals(new DateTime()))
                    {
                        DicProcess[Constants.PROCESS_ANES_END].TimeText = DataManager.Instance.CurrentPatientLink.Status.MazuiEndTime.ToString(DateFormat.DATE_FORMAT_STR_HM);
                        DicProcess[Constants.PROCESS_ANES_END].State = false;
                    }
                    else
                    {
                        DicProcess[Constants.PROCESS_ANES_END].State = true;
                    }
                }
                else
                {
                    DicProcess[Constants.PROCESS_ANES_START].State = true;
                    DicProcess[Constants.PROCESS_ANES_END].State = false;
                }

                 (DataManager.Instance.AnesRecordCtrl.ViewModel as AnesRecordCtrlViewModel).InitData();
            }
            else
            {
                FunctionListHeaderCtrlViewModel.Instance.DisplayButton(true, FunctionListButton.刷新);
            }
        }

        /// <summary>
        /// 检查页面，保持事件与进度条统一
        /// </summary>
        private void CheckEventAndTitle()
        {
            PatientEventsModel pem = null;
            DateTime inRoomTime = GetPatientLink().Status.InRoomTime;
            DateTime outRoomTime = GetPatientLink().Status.OutRoomTime;
            if (!inRoomTime.Equals(new DateTime()))
            {
                pem = GetEventByCode(Constants.EVENT_IN_ROOM);
                if (pem == null)
                {
                    AddEvent(Constants.EVENT_IN_ROOM, inRoomTime, false, false);
                    if (!outRoomTime.Equals(new DateTime()))
                    {
                        AddEvent(Constants.EVENT_IN_ROOM, outRoomTime, false, true);
                    }
                }
                else
                {
                    pem.BeginTime = inRoomTime;
                    if (!outRoomTime.Equals(new DateTime()))
                    {
                        pem.EndTime = outRoomTime;
                    }
                    PatientEventsService.Instance.AddUpdate(pem);
                    OperationDataPool.Instance.CurOperationData.EventDataCache.AddUpdateEvent(pem);
                }
            }

            pem = null;
            DateTime anesStartTime = GetPatientLink().Status.MazuiStartTime;
            DateTime anesEndTime= GetPatientLink().Status.MazuiEndTime;
            if (!anesStartTime.Equals(new DateTime()))
            {
                pem = GetEventByCode(Constants.EVENT_ANES);
                if (pem == null)
                {
                    AddEvent(Constants.EVENT_ANES, anesStartTime, false, false);
                    if (!anesEndTime.Equals(new DateTime()))
                    {
                        AddEvent(Constants.EVENT_ANES, anesEndTime, false, true);
                    }
                }
                else
                {
                    pem.BeginTime = anesStartTime;
                    if (!anesEndTime.Equals(new DateTime()))
                    {
                        pem.EndTime = anesEndTime;
                    }
                    PatientEventsService.Instance.AddUpdate(pem);
                    OperationDataPool.Instance.CurOperationData.EventDataCache.AddUpdateEvent(pem);
                    
                }
            }

            pem = null;
            DateTime operStartTime = GetPatientLink().Status.OperStartTime;
            DateTime operEndTime = GetPatientLink().Status.OperEndTime;
            if (!operStartTime.Equals(new DateTime()))
            {
                pem = GetEventByCode(Constants.EVENT_OPERATION);
                if (pem == null)
                {
                    AddEvent(Constants.EVENT_OPERATION, operStartTime, false, false);
                    if (!operEndTime.Equals(new DateTime()))
                    {
                        AddEvent(Constants.EVENT_OPERATION, operEndTime, false, true);
                    }
                }
                else
                {
                    pem.BeginTime = operStartTime;
                    if (!operEndTime.Equals(new DateTime()))
                    {
                        pem.EndTime = operEndTime;
                    }
                    PatientEventsService.Instance.AddUpdate(pem);
                    OperationDataPool.Instance.CurOperationData.EventDataCache.AddUpdateEvent(pem);
                }
            }
        }

        /// <summary>
        /// 
        /// 
        /// </summary>
        /// <returns></returns>
        private PatientEventsModel GetEventByCode(string code)
        {
            PatientEventsModel pem = null;
            DateTime startTime = PatientLink.Status.InRoomTime;
            DateTime anesStartTime = PatientLink.Status.AnesRecordStartTime;
            DateTime endTime;
            if (!PatientLink.Status.OutRoomTime.Equals(new DateTime()))
            {
                endTime = PatientLink.Status.OutRoomTime;
            }
            else
            {
                endTime = anesStartTime.AddHours((PatientLink.Status.TotalPage) * 4);
            }
            List<PatientEventsModel> eventList = PatientEventsService.Instance.GetPatientEvents8Time(PatientLink.Id.ToString(), startTime, endTime);
            foreach (var item in eventList)
            {
                if (code.Equals(item.Code))
                {
                    pem = item;
                }
            }
            return pem;

        }

        /// <summary>
        /// 流程控制按钮触发
        /// </summary>
        /// <param name="buttonName"></param>
        public void ClickProcessButton(string buttonName)
        {
            if (string.IsNullOrEmpty(buttonName))
            {
                return;
            }

            switch (buttonName)
            {
                case Constants.PROCESS_INROOM:
                    InRoomClick();
                    break;

                case Constants.PROCESS_ANES_START:
                    AnesStartClick();
                    break;

                case Constants.PROCESS_OPER_START:
                    OperStartClick();
                    break;

                case Constants.PROCESS_OPER_END:
                    OperEndClick();
                    break;

                case Constants.PROCESS_ANES_END:
                    AnesEndClick();
                    break;

                case Constants.PROCESS_OUTROOM:
                    OutRoomClick();
                    break;
            }
        }
        /// <summary>
        /// 事件发生变化
        /// </summary>
        /// <param name="code"></param>
        /// <param name="isEnd"></param>
        public void ChangeEvent(string code, bool isEnd)
        {
            if (DataManager.Instance.CurrentHospital.HospitalCode.Equals(HospitalConfig.HOSPITAL_CODE_CQ_FYBJY))
            {
                int totalPage = DataManager.Instance.CurrentPatientLink.Status.TotalPage;
                RefCurTatalPage();
                int CurTotalPage = DataManager.Instance.CurrentPatientLink.Status.TotalPage;
                if (totalPage != CurTotalPage)
                {
                    Refresh();
                    return;
                }
            }
            if (code.Equals(Constants.EVENT_IN_ROOM))
            {
                //List<PatientEventsModel> inAndOutRoomEvents = OperationDataPool.Instance.CurOperationData.EventDataCache.SearchEventExeByCode(Constants.EVENT_IN_ROOM);
                //if (inAndOutRoomEvents != null && inAndOutRoomEvents.Count > 0)
                //{
                //    PatientEventsModel eventExe = inAndOutRoomEvents.First();
                //    if (!isEnd)
                //    {
                //        DicProcess[Constants.PROCESS_INROOM].TimeText = eventExe.BeginTime.ToString(DateFormat.DATE_FORMAT_STR_HM);
                //        DicProcess[Constants.PROCESS_INROOM].State = false;

                //        DicProcess[Constants.PROCESS_OUTROOM].TimeText = "--/ --";
                //        DicProcess[Constants.PROCESS_OUTROOM].State = true;
                //    }
                //    else
                //    {
                //        DicProcess[Constants.PROCESS_INROOM].TimeText = eventExe.BeginTime.ToString(DateFormat.DATE_FORMAT_STR_HM);
                //        DicProcess[Constants.PROCESS_INROOM].State = false;

                //        DicProcess[Constants.PROCESS_OUTROOM].TimeText = eventExe.EndTime.ToString(DateFormat.DATE_FORMAT_STR_HM);
                //        DicProcess[Constants.PROCESS_OUTROOM].State = false;
                //    }
                //}
                //else
                //{
                //    DicProcess[Constants.PROCESS_INROOM].TimeText = "--/ --";
                //    DicProcess[Constants.PROCESS_INROOM].State = true;

                //    DicProcess[Constants.PROCESS_OUTROOM].TimeText = "--/ --";
                //    DicProcess[Constants.PROCESS_OUTROOM].State = false;
                //}
                Refresh();
                return;
            }

            if (code.Equals(Constants.EVENT_ANES))
            {
                List<PatientEventsModel> anesEvents = OperationDataPool.Instance.CurOperationData.EventDataCache.SearchEventExeByCode(Constants.EVENT_ANES);
                if (anesEvents != null && anesEvents.Count > 0)
                {
                    PatientEventsModel eventExe = anesEvents.First();
                    if (!isEnd)
                    {
                        DicProcess[Constants.PROCESS_ANES_START].TimeText = eventExe.BeginTime.ToString(DateFormat.DATE_FORMAT_STR_HM);
                        DicProcess[Constants.PROCESS_ANES_START].State = false;

                        DicProcess[Constants.PROCESS_ANES_END].TimeText = "--/ --";
                        DicProcess[Constants.PROCESS_ANES_END].State = true;
                    }
                    else
                    {
                        DicProcess[Constants.PROCESS_ANES_START].TimeText = eventExe.BeginTime.ToString(DateFormat.DATE_FORMAT_STR_HM);
                        DicProcess[Constants.PROCESS_ANES_START].State = false;

                        if (eventExe.EndTime.Equals(new DateTime()))
                        {
                            DicProcess[Constants.PROCESS_ANES_END].TimeText = "--/ --";
                            DicProcess[Constants.PROCESS_ANES_END].State = true;
                        }
                        else
                        {
                            DicProcess[Constants.PROCESS_ANES_END].TimeText = eventExe.EndTime.ToString(DateFormat.DATE_FORMAT_STR_HM);
                            DicProcess[Constants.PROCESS_ANES_END].State = false;
                        }

                    }
                }
                else
                {
                    DicProcess[Constants.PROCESS_ANES_START].TimeText = "--/ --";
                    DicProcess[Constants.PROCESS_ANES_START].State = true;

                    DicProcess[Constants.PROCESS_ANES_END].TimeText = "--/ --";
                    DicProcess[Constants.PROCESS_ANES_END].State = false;
                }
                CalTimeSpan();
                SaveOper2DB();
            }


            if (code.Equals(Constants.EVENT_OPERATION))
            {
                List<PatientEventsModel> operEvents = OperationDataPool.Instance.CurOperationData.EventDataCache.SearchEventExeByCode(Constants.EVENT_OPERATION);
                if (operEvents != null && operEvents.Count > 0)
                {
                    PatientEventsModel eventExe = operEvents.First();
                    if (!isEnd)
                    {
                        DicProcess[Constants.PROCESS_OPER_START].TimeText = eventExe.BeginTime.ToString(DateFormat.DATE_FORMAT_STR_HM);
                        DicProcess[Constants.PROCESS_OPER_START].State = false;

                        DicProcess[Constants.PROCESS_OPER_END].TimeText = "--/ --";
                        DicProcess[Constants.PROCESS_OPER_END].State = true;
                    }
                    else
                    {
                        DicProcess[Constants.PROCESS_OPER_START].TimeText = eventExe.BeginTime.ToString(DateFormat.DATE_FORMAT_STR_HM);
                        DicProcess[Constants.PROCESS_OPER_START].State = false;
                        if (eventExe.EndTime.Equals(new DateTime()))
                        {
                            DicProcess[Constants.PROCESS_OPER_END].TimeText = "--/ --";
                            DicProcess[Constants.PROCESS_OPER_END].State = true;
                        }
                        else
                        {
                            DicProcess[Constants.PROCESS_OPER_END].TimeText = eventExe.EndTime.ToString(DateFormat.DATE_FORMAT_STR_HM);
                            DicProcess[Constants.PROCESS_OPER_END].State = false;
                        }
                    }
                }
                else
                {
                    DicProcess[Constants.PROCESS_OPER_START].TimeText = "--/ --";
                    DicProcess[Constants.PROCESS_OPER_START].State = true;

                    DicProcess[Constants.PROCESS_OPER_END].TimeText = "--/ --";
                    DicProcess[Constants.PROCESS_OPER_END].State = false;
                }
                CalTimeSpan();
                SaveOper2DB();
            }
        }

        /// <summary>
        ///根据所有事件来改变页数
        /// </summary>
        /// <returns></returns>
        private void RefCurTatalPage()
        {
            DateTime date = DateTime.Now;
            DateTime anesStartTime = DataManager.Instance.CurrentPatientLink.Status.AnesRecordStartTime;
            int totalPage = DataManager.Instance.CurrentPatientLink.Status.TotalPage;
            List<PatientEventsModel> eventList = OperationDataPool.Instance.CurOperationData.EventDataCache.SearchAllEventExe();
            foreach (var item in eventList)
            {
                ConfigEventsModel cem = null;
                if (DataManager.Instance.Code2events.ContainsKey(item.Code))
                {
                    cem = DataManager.Instance.Code2events[item.Code];
                }
                if (cem == null)
                {
                    continue;
                }
                else
                {
                    if (cem.Single)
                    {
                        if (item.BeginTime > date)
                        {
                            date = item.BeginTime;
                        }
                    }
                    else
                    {
                        if (item.BeginTime > date)
                        {
                            date = item.BeginTime;
                        }
                        if (item.EndTime > date)
                        {
                            date = item.EndTime;
                        }
                    }
                }
            }
            if (!DataManager.Instance.CurrentPatientLink.Status.OutRoomTime.Equals(new DateTime()))
            {
                date = DataManager.Instance.CurrentPatientLink.Status.OutRoomTime;
            }
            TimeSpan span = date - anesStartTime;
            int minutes = span.Days * 24 * 60 + span.Hours * 60 + span.Minutes;
            if (minutes < 0)
            {
                minutes = 0;
            }
            int temp = minutes % (4 * 60);
            int CurtotalPage = 0;
            if (temp == 0 && minutes != 0)
            {
                CurtotalPage = (int)minutes / (4 * 60);
            }
            else
            {
                CurtotalPage = (int)minutes / (4 * 60) + 1;
            }
            if (CurtotalPage != totalPage)
            {
                DataManager.Instance.CurrentPatientLink.Status.TotalPage = CurtotalPage;
                SaveOper2DB();
            }
        }

        /// <summary>
        /// 彻底删除手术
        /// </summary>
        public void DeleteOper()
        {
            GetPatientLink().Patient.Status = Constants.FLAG_IN_VALID;
            GetPatientLink().Application.Detailstatus = Constants.OR_STATUS_FLAG_DISCHARGED;
            GetPatientLink().Status.DischargeTime = DateTime.Now;
            SaveOper2DB();
            HospitalReturnUtil.Instance.ReturnOperStatus2His(GetPatientLink());


        }

        /// <summary>
        /// 取消手术
        /// </summary>
        public void CancelOper()
        {
            string oldStatus = GetPatientLink().Application.Detailstatus;
            if (!Constants.OR_STATUS_FLAG_IN_ROOM.Equals(oldStatus))
            {
                return;
            }
            GetPatientLink().Application.Detailstatus = Constants.OR_STATUS_FLAG_SCHEDULED;
            GetPatientLink().Application.Status = Constants.AP_STATUS_MAZUIQIAN;
            GetPatientLink().Status.CancelTime = DateTime.Now;

            DelAllExe();
            SaveOper2DB();
        }



        /// <summary>
        /// 跳转至选择手术界面
        /// </summary>
        public void GotoSelOperCtrl()
        {
            MainPageCommonViewModel.Instance.NavigateTo("XuanZeShouShuCtrl", true);
        }
        /// <summary>
        /// 取消采集
        /// </summary>
        public void StopReadVitalCapture()
        {

            VitalSignCapture.Instance.StopCapture();

        }

        public PatientLinkModel GetPatientLink()
        {
            return DataManager.Instance.CurrentPatientLink == null ? null : DataManager.Instance.CurrentPatientLink;
        }

        /// <summary>
        /// 静脉麻醉关联麻醉单
        /// </summary>
        public void InitInRoom4IVAnes(DateTime date)
        {
            InRoom(date);
            AddEvent(Constants.EVENT_IN_ROOM, date, false, false);
        }

        public void InitOutRoom4IVAnes(DateTime date)
        {
            OutRoom(date);
            AddEvent(Constants.EVENT_IN_ROOM, date, false, true);
        }




        #endregion


        #region EventHandlers


        #endregion
    }
    public class CommonBtnCtrlModel : ObservableObject
    {
        /// <summary>
        /// 按钮显示
        /// </summary>
        private string name;

        /// <summary>
        /// 按钮状态
        /// </summary>
        private bool state;

        /// <summary>
        /// 时间显示
        /// </summary>
        private string timeText;

        /// <summary>
        /// 图片路径
        /// </summary>
        private string imageUrl;

        public CommonBtnCtrlModel(string buttonName, bool showState, string timeText = "", string imageUrl = "")
        {
            Name = buttonName;
            State = showState;
            TimeText = timeText;
            ImageUrl = imageUrl;
        }

        public string Name
        {
            get
            {
                return name;
            }

            set
            {

                name = value;
                RaisePropertyChanged("Name");
            }
        }

        public bool State
        {
            get
            {
                return state;
            }

            set
            {

                state = value;
                RaisePropertyChanged("State");
            }
        }

        public string TimeText
        {
            get
            {
                return timeText;
            }

            set
            {
                timeText = value;
                RaisePropertyChanged("TimeText");
            }
        }

        public string ImageUrl
        {
            get
            {
                return imageUrl;
            }

            set
            {
                imageUrl = value;
            }
        }
    }

}
